package com.eques.util

import com.eques.icvss.utils.ELog
import okhttp3.*
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaType
import java.io.IOException
import java.util.concurrent.TimeUnit

object HttpUtil {
    private val TAG:String="EquesR100_Net："
    private val client: OkHttpClient by lazy {
        OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build()
    }

    // 异步GET请求
    fun getAsync(
        url: String,
        params: Map<String, String>? = null,
        callback: (Result<String>) -> Unit
    ) {
        ELog.e(TAG, "get:$url")
        val request = buildGetRequest(url, params)
        executeAsync(request, callback)
    }

    // 异步POST请求（表单提交）
    fun postAsync(
        url: String,
        params: Map<String, String>? = null,
        callback: (Result<String>) -> Unit
    ) {
        ELog.e(TAG, "post:$url")
        val request = buildPostRequest(url, params)
        executeAsync(request, callback)
    }

    // 构建GET请求对象
    private fun buildGetRequest(url: String, params: Map<String, String>?): Request {
        val httpUrl = url.toHttpUrlOrNull()?.newBuilder()?.apply {
            params?.forEach { (key, value) -> addQueryParameter(key, value) }
        }?.build() ?: throw IllegalArgumentException("Invalid URL")

        return Request.Builder()
            .url(httpUrl)
            .get()
            .build()
    }

    // 构建POST请求对象
    private fun buildPostRequest(url: String, params: Map<String, String>?): Request {
        val formBody = FormBody.Builder().apply {
            params?.forEach { (key, value) -> add(key, value) }
        }.build()

        return Request.Builder()
            .url(url)
            .post(formBody)
            .build()
    }

    // 执行异步请求
    private fun executeAsync(request: Request, callback: (Result<String>) -> Unit) {
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                callback(Result.failure(e))
            }

            override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (response.isSuccessful) {
                        val result= response.body?.string();
                        ELog.e(TAG, result)
                        result?.let {
                            callback(Result.success(it))
                        } ?: callback(Result.failure(IOException("Empty response body")))
                    } else {
                        callback(Result.failure(IOException("HTTP ${response.code}")))
                    }
                }
            }
        })
    }

    // 新增JSON MediaType
    private val JSON_MEDIA_TYPE = "application/json; charset=utf-8".toMediaType()

    // 异步POST请求（JSON提交）
    fun postJsonAsync(
        url: String,
        jsonBody: String,
        callback: (Result<String>) -> Unit
    ) {
        ELog.e(TAG, "post json:$url")
        ELog.e(TAG, "post json data:$jsonBody")
        val request = buildJsonRequest(url, jsonBody)
        executeAsync(request, callback)
    }

    // 构建JSON请求对象
    private fun buildJsonRequest(url: String, jsonBody: String): Request {
        val httpUrl = url.toHttpUrlOrNull()
            ?: throw IllegalArgumentException("Invalid URL: $url")

        val requestBody = RequestBody.create(JSON_MEDIA_TYPE, jsonBody)

        return Request.Builder()
            .url(httpUrl)
            .post(requestBody)
            .build()
    }
}

